﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
namespace MezmurStore2.Utility
{
    public class BlobStoreFileManager : IFileStoreManager
    {
        public string UploadFile(System.IO.Stream fileStream, string folderName, string fileName, string contentType)
        {
            fileStream.Seek(0, System.IO.SeekOrigin.Begin);
            
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            
            var blobClient = storageAccount.CreateCloudBlobClient();
            // Retrieve a reference to a container 
            var container = blobClient.GetContainerReference(folderName.ToLower());

            // Create the container if it doesn't already exist
            container.CreateIfNotExist();
            container.SetPermissions(
                new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            var blob = container.GetBlobReference(fileName);
            if (contentType != null)
            {
                blob.Properties.ContentType = contentType;
            }
            blob.UploadFromStream(fileStream, new BlobRequestOptions() { });
            
            var resultBlob = container.ListBlobs().First(b => b.Uri.AbsoluteUri.ToLower().Contains(fileName.ToLower()));
            return resultBlob.Uri.AbsoluteUri;
        }
    }
}